#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "buildin.h"

static buildin_func_t fun_cd, fun_exit, fun_export;
static char **environ;

struct buildin_st buildin[]={
	{"cd", fun_cd},
	{"exit", fun_exit},
	{"export",fun_export},
	{NULL, NULL},
};

int buildin_index(struct cmd_st *ptr)
{
	int i;

	for (i=0;buildin[i].cmdstr!=NULL;++i)
	{
		if (strcmp(buildin[i].cmdstr, ptr->glob_res.gl_pathv[0])==0)
		{
			return i;
		}
	}
	return -1;
}

static int fun_cd(struct cmd_st *ptr)
{
	if (ptr->glob_res.gl_pathc>=2)
	{
		return chdir(ptr->glob_res.gl_pathv[1]);
	}
	else
	{
		return chdir(getenv("HOME"));
	}
}

static int fun_exit(struct cmd_st *ptr)
{
	if (ptr->glob_res.gl_pathc>=2)
	{
		exit(atoi(ptr->glob_res.gl_pathv[1]));
	} 
	else
	{
		exit(0);
	}
}

static int fun_export(struct cmd_st *ptr)
{
	int i;
	int ret;
	if (ptr->glob_res.gl_pathc == 3)
	{
	    ret = setenv(ptr->glob_res.gl_pathv[1],ptr->glob_res.gl_pathv[2],1);	     
	} 
	else 
	{
		return -1;
	}
	return 0;
}
